<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-card class="box-card">
      <el-form :model="queryParams" :inline="true" ref="queryForm" size="small" v-show="showSearch"
               label-width="98px">
        <el-form-item label="产品编码" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入产品编码" style="width: 150px;"
                    clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入产品名称" style="width: 150px;"
                    clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="产品型号" prop="model">
          <el-input v-model="queryParams.model" placeholder="请输入产品型号" style="width: 150px;"
                    clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="submitForm">添 加</el-button>
          <el-button type="info" icon="el-icon-upload2" size="mini" @click="showUploadDialog">导 入</el-button>
        </el-form-item>
      </el-form>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-table border v-loading="loading" :data="columns" @selection-change="handleSelectionChange"
                  :max-height="400" @sort-change="handleSortChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column sortable label="产品编码" align="center" prop="code"/>
          <el-table-column sortable label="产品名称" align="center" prop="name" />
          <el-table-column sortable label="产品型号" align="center" prop="model"/>
          <el-table-column label="内部编码" align="center" prop="innerGoodsId" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.innerGoodsId" placeholder="请选择产品" style="width: 100%;"
                         reserve-keyword filterable  clearable>
                <el-option v-for="item in scope.row.innerGoods"
                           :key="item.id" :label="item.code" :value="item.id"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="工程名称" align="center" prop="gongchengName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.gongchengName" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="合同物料名称" align="center" prop="contractGoodsName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.contractGoodsName" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="合同收货人" align="center" prop="deliveryPerson" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.deliveryPerson" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="项目单位" align="center" prop="projectDept" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.projectDept" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="合同交货日期" align="center" prop="deliveryTime" width="150">
            <template slot-scope="scope">
              <el-date-picker clearable style="width: 130px"
                              size="mini"
                              v-model="scope.row.deliveryTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="交货日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="销售单价（不含税）" align="center" prop="goodsUnitPrice" width="150">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.goodsUnitPrice" size="mini" :min="0"
                               @change="handleChangeMoney(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="销售单价（含税）" align="center" prop="goodsTaxUnitPrice" width="150">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.goodsTaxUnitPrice" size="mini" :min="0"
                               @change="handleChangeTaxMoney(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="销售数量" align="center" prop="counts" width="150">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.counts" size="mini"
                               @change="handleChangeCount(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="销售总价（不含税）" align="center" prop="goodsTotalPrice"/>
          <el-table-column label="销售总价（含税）" align="center" prop="goodsTaxTotalPrice"/>
          <el-table-column label="备注" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" size="mini"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <el-card class="box-card">
      <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2"
                show-summary :summary-method="getSummaries" max-height="700">
        <el-table-column align="center" label="序号" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ (queryParams2.pageNum - 1) * queryParams2.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="产品编码" prop="goodsCode"/>
        <el-table-column align="center" label="内部编码" prop="innerGoodsCode"/>
        <el-table-column align="center" label="工程名称" prop="gongchengName" show-overflow-tooltip/>
        <el-table-column align="center" label="产品名称" prop="goodsName"/>
        <el-table-column align="center" label="合同物料名称" prop="contractGoodsName"/>
        <el-table-column align="center" label="项目单位" prop="projectDept" show-overflow-tooltip/>
        <el-table-column align="center" label="产品型号" prop="model"/>
        <el-table-column align="center" label="产品单位" prop="unit"/>
        <el-table-column align="center" label="销售单价（不含税）" prop="goodsUnitPrice"/>
        <el-table-column align="center" label="销售单价（含税）" prop="goodsTaxUnitPrice"/>
        <el-table-column label="销售数量" align="center" prop="orderCount" width="150"/>
        <el-table-column label="销售总价（不含税）" align="center" prop="goodsTotalPrice"/>
        <el-table-column label="销售总价（含税）" align="center" prop="goodsTaxTotalPrice"/>
        <el-table-column label="需求日期" align="center" prop="deliveryTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150" align="center" prop="remark" show-overflow-tooltip/>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-popconfirm :title="`确认删除 `+scope.row.goodsName+` 数据项？`" @confirm="handleDelete(scope.row)"
                           style="margin-left: 10px;">
              <el-button icon="el-icon-delete" size="mini" slot="reference" type="text"
                         v-hasPermi="['develop:ProjectBaseInfo:remove']">删除
              </el-button>
            </el-popconfirm>
            <el-button style="margin-left: 20px;" v-if="scope.row.status==='0'" size="mini" type="text"
                       icon="el-icon-edit" @click="editGoods(scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitProject" v-if="">提交审核到库管</el-button>
      <el-button @click="cancel">暂存订单</el-button>
    </div>
    <upload-dialog ref="uploadDialog" @ok="getList2" @handleFileSuccess="handleFileSuccess"></upload-dialog>
    <edit-goods-form @ok="getList2" ref="editGoodsForm"></edit-goods-form>
  </el-dialog>
</template>

<script>
import UploadDialog from "@/views/upload/UploadDialog";
import {accAdd, accMul, accDiv, addAction, deleteAction, getAction, getById, updateAction} from '@/api/manage'
import EditGoodsForm from '@/views/develop/projectBaseInfo/module/EditGoodsForm.vue'; // 引入 EditGoodsForm 组件

export default {
  name: "GoodsChoseFormList",
  dicts: ['goods_customer', 'company', 'yes_no', 'buy_type', 'goods_type'],
  components: {
    UploadDialog,
    EditGoodsForm // 注册 EditGoodsForm 组件
  },
  data() {
    return {
      // 遮罩层
      title: "产品1选择",
      loading: false,
      open: false,
      // 选中数组
      ids: [],
      proId: "",
      proStatus: "",
      saleType: "2",
      goodsType: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息管理表格数据
      dataList: [],
      columns: [],
      rules: {},
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        model: null,
        brand: null,
        unit: null,
        costPrice: null,
        count: null,
        cost: null,
        validityTerm: null,
        buyId: null,
        buyName: null,
        buyDate: null,
        buyType: null,
        reimburse: null,
        supplierId: null,
        supplierName: null,
        params: {
          dataFlag: "1"
        }
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 1000,
        id: null,
        name: null,
        model: null,
        brand: null,
        taxNo: null,
        addr: null,
        tel: null,
        bankName: null,
        bankNo: null,
        info: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        type: null,
        orderByColumn: "sort",
        isAsc: "asc"
      },
      total2: '',
      loading2: '',
      columns2: [],
      innerGoodsList: [],
      url: {
        list: '/goodsOrderIn/goodsOrderIn/list',
        remove: '/goodsOrderIn/goodsOrderIn/',
        export: '/goodsOrderIn/goodsOrderIn/export',
        insertForPrjNew: '/goodsSale/goodsSale/insertForPrjNew',
        list2: '/goodsSale/goodsSale/listSaleProject',
        remove2: '/goodsSale/goodsSale/deleteById/',
        submitProject: '/projectBaseInfo/projectBaseInfo/submitProject',
        innerGoodsList: '/goodsOrderInner/goodsOrderInner/list',

      },
      tableMaxHeight: window.innerHeight - 900,
    };
  },
  created() {

  },
  methods: {

    editGoods(row) {
      this.$refs.editGoodsForm.show(row);
    }, /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },
    handleFileSuccess(response, file, fileList) {
      this.$refs.uploadDialog.open = false;
      this.$refs.uploadDialog.isUploading = false;
      if (response.data.code == "200") {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
      } else {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
      }
      this.getList2();
    },
    showUploadDialog() {
      this.$refs.uploadDialog.title = "信息导入";
      this.$refs.uploadDialog.tmplName = "产品模板.xlsx";
      this.$refs.uploadDialog.fileName = "产品模板.xlsx";
      this.$refs.uploadDialog.uploadUrl = "/goodsSale/goodsSale/importData?projectId=" + this.proId;
      this.$refs.uploadDialog.show();
    },
    getList2() {
      this.loading2 = true;
      /*getById(this.url.listBatch, this.ids).then(response => {
        this.columns = response.rows;
        this.total = response.total;
        this.loading = false;
      });*/
      this.queryParams2.projectId = this.proId
      getAction(this.url.list2, this.queryParams2).then(response => {
        this.columns2 = response.rows;
        this.total2 = response.total;
        this.loading2 = false;
      });
    },
    handleUpdate(row) {
      const id = row.id || this.ids;
      this.proId = id;
      this.open = true;
      this.loading = false;
      this.proStatus = row.status;
      this.goodsType = row.goodsType;
      // this.chose(this.proId, "2");
      this.columns = [];
      this.columns2 = [];
      this.getList2();
    },
    refreshPageData() {
      let that = this;
      let param = {
        id: that.proId
      }
      that.handleUpdate(param);

    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove2, ids).then(response => {
        this.refreshPageData();
        this.$modal.msgSuccess("删除成功");
        this.handleQuery();
      }).catch(() => {
      });
    },
    handleChangeMoney(row) {
      let that = this;
      let handleReckonMoney = (row) => {
        let row_money = 0;
        let row_tax_money = 0;
        row_money = accMul(Number(row.goodsUnitPrice), Number(row.counts))
        that.$set(row, 'goodsTotalPrice', row_money);
        row_money = accMul(Number(row.goodsUnitPrice), Number(1.13))
        that.$set(row, 'goodsTaxUnitPrice', row_money);
        row_tax_money = accMul(Number(row.goodsTaxUnitPrice), Number(row.counts))
        that.$set(row, 'goodsTaxTotalPrice', row_tax_money);
      };
      handleReckonMoney(row);
    },


    handleChangeTaxMoney(row) {
      let that = this;
      let handleReckonMoney = (row) => {
        let unitPrice = accDiv(Number(row.goodsTaxUnitPrice), Number(1.13)).toFixed(3);
        let totalPrice = accMul(unitPrice, Number(row.counts)).toFixed(3);
        let totalTaxPrice = accMul(Number(row.goodsTaxUnitPrice), Number(row.counts)).toFixed(3);
        that.$set(row, 'goodsUnitPrice', unitPrice);
        that.$set(row, 'goodsTotalPrice', totalPrice);
        that.$set(row, 'goodsTaxTotalPrice', totalTaxPrice);
      };
      handleReckonMoney(row);
    },

    handleChangeCount(row) {
      let that = this;
      let handleReckonMoney = (row) => {
        let unitPrice = Number(row.goodsUnitPrice);
        let unitTaxPrice = Number(row.goodsTaxUnitPrice);
        let totalPrice = accMul(unitPrice, Number(row.counts)).toFixed(3);
        let totalTaxPrice = accMul(unitTaxPrice, Number(row.counts)).toFixed(3);
        that.$set(row, 'goodsUnitPrice', unitPrice);
        that.$set(row, 'goodsTotalPrice', totalPrice);
        that.$set(row, 'goodsTaxTotalPrice', totalTaxPrice);
      };
      handleReckonMoney(row);
    },

    chose(proId, type) {
      this.open = true;
      this.proId = proId;
      this.saleType = type;
      this.getList();
    },
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        let res = response.rows;
        for (let i = 0; i < res.length; i++) {
          res[i].buyDate = new Date();
          res[i].goodsTaxTotalPrice = 0;
        }
        this.columns = res;
        this.total = response.total;
        this.loading = false;
        this.getInnerGoodsList();
      });
    },


    getInnerGoodsList() {
      this.loading = true;
      let params={
        "pageSizeZero":true,
      };
      getAction(this.url.innerGoodsList, params).then(response => {
        this.innerGoodsList = response.rows;
        this.loading = false;
        for (let i = 0; i < this.columns.length; i++) {
          let innerGoods = [];
          for (let j = 0; j < this.innerGoodsList.length; j++) {
            if (this.columns[i].id == this.innerGoodsList[j].goodsId) {
              innerGoods.push(this.innerGoodsList[j]);
            }
          }
          this.$set(this.columns[i], "innerGoods", innerGoods);
        }
      });
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$emit('ok');
      // this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.dataList = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    submitProject() {
      if (this.columns2.length === 0) {
        this.$modal.msgError("请先选择产品再提交！");
        return;
      }
      let goodsSaleIds = [];
      for (let i = 0; i < this.columns2.length; i++) {
        goodsSaleIds.push(this.columns2[i].id);
      }
      const params = {};
      params.goodsSaleIds = goodsSaleIds.toString();
      params.id = this.proId;
      params.status = "1";
      // params.goodsType = this.goodsType;

      getAction(this.url.submitProject, params).then(response => {
        this.refreshPageData();
        this.$modal.msgSuccess("提交成功!");
        this.open = false;
        this.handleQuery();

        this.$parent.getList()
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      let that = this;
      const ids = this.ids;
      if (ids == null || ids == '' || ids == 'undefined') {
        that.$modal.msgError("请选择一条记录");
        return;
      }
      let arrays = that.dataList;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].counts === 0) {
          that.$modal.msgError(arrays[i].name + "订单数量不能为0");
          return;
        }
      }
      that.$refs["form"].validate(valid => {
        if (valid) {
          const goodsOrderIn = Object.assign({});
          goodsOrderIn.projectId = that.proId;
          goodsOrderIn.type = that.saleType;
          goodsOrderIn.columns = that.dataList;
          addAction(that.url.insertForPrjNew, goodsOrderIn).then(response => {
            that.$modal.msgSuccess("添加成功");
            // this.open = false;
            that.$emit('ok');
            that.getList2();
            that.handleQuery();
          });
        }
      });
    },

    getSummaries(param) {
      // console.log(param);
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "orderCount" || column.property === "goodsTotalPrice" || column.property === "goodsTaxTotalPrice") {

          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },


  }
};
</script>
